<template>
  <div class="app-container">
    <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { reqEmployeesUploadExcel } from '@/api/employees'
import moment from 'moment'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$router.query.type
    }
  },
  methods: {
    // 这个函数在进行上传文件大小的校验
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      // results中的字段都是中文, 发送请求需要携带的是英文的字段
      // 对应关系
      // 根据路由地址参数的type参数值 走不同的上传业务
      if (this.type === 'user') {
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const arr = results.map(item => {
          const obj = {}
          for (const k in item) {
            const englishKey = userRelations[k] // 取到英文的键
            if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
              obj[englishKey] = moment(this.formatExcelDate(item[k], '-')).add(1, 'days').format('YYYY-MM-DD')
            } else {
              obj[englishKey] = item[k]
            }
          }
          return obj
        })
        await reqEmployeesUploadExcel(arr)
        // 跳转到员工列表页面 gp(1) forward()
        // this.$router.go(-1)
        this.$router.back()
      }
      if (this.type === 'att') {
        console.log('考勤上传')
      }
    },
    // 处理excel上传日期格式的处理函数(execl起始时间1900-1-1,计算机是1970-1-1)
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
